import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:sciolto/POJO/Song.dart';
import 'package:sciolto/POJO/SongList.dart';
import 'package:sciolto/api/Common_api.dart';
import 'package:sciolto/api/music.dart';
import 'package:sciolto/util/setting.dart';
import 'package:sciolto/widget/custom_route.dart';

class SonglistSelectPage extends StatefulWidget {
  final SongList _songList;

  SonglistSelectPage(this._songList);

  @override
  State<StatefulWidget> createState() => _SonglistSelectPageState();
}

class _SonglistSelectPageState extends State<SonglistSelectPage> {
  double _width, _height, _x, _y;

  List<SongList> _listOfSonglist;

  bool _hasLoaded = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _hasLoaded = false;
    SongsInfo().getSongLists().then((value) {
      _hasLoaded = true;
      _listOfSonglist = value
        ..removeWhere((element) => element.listName == '全部歌曲');
      setState(() {});
    });
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    Size size = CommonApi.initParameter(context);
    _width = size.width;
    _height = size.height;
    _x = _width / 420;
    _y = _height / 800;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            height: 20 * _y,
          ),
          _titleBar(),
          Expanded(
            flex: 1,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 10 * _y),
              child: Column(
                children: [
                  _defaultSonglistItem(
                      imagePath: "images/download.png", title: "全部歌曲"),
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      "我的歌单",
                      style: TextStyle(
                          fontSize: 17 * _y,
                          color: Colors.blueGrey,
                          fontWeight: FontWeight.w900),
                    ),
                  ),
                  _customSonglistListView()
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  // TODO: 标题栏
  Widget _titleBar() {
    return Container(
      width: _width,
      height: 50 * _y,
      color: Setting.themeColor,
      child: Stack(
        children: [
          Center(
            child: Text(
              "将歌曲添加到歌单",
              style: TextStyle(
                  fontSize: 20 * _y,
                  color: Colors.cyan,
                  fontWeight: FontWeight.w800),
            ),
          ),
          Positioned.fill(
              child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Spacer(
                flex: 1,
              ),
              TextButton(
                onPressed: _onPressComplete,
                child: Text(
                  "完成",
                  style: TextStyle(fontSize: 17 * _y, color: Colors.cyan),
                ),
              ),
            ],
          ))
        ],
      ),
    );
  }

  // TODO: 默认歌单选择
  Widget _defaultSonglistItem(
      {@required String imagePath, @required String title}) {
    return Ink(
      color: Colors.grey[50],
      child: InkWell(
        splashColor: Colors.cyan[100],
        onTap: () => _onTapSonglist(context, SongList(title, null, null, null)),
        child: Container(
            padding: EdgeInsets.all(3.0),
            width: _width,
            height: 70 * _y,
            alignment: Alignment.center,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                          alignment: Alignment.center,
                          height: 60 * _y,
                          width: 60 * _y,
                          padding: EdgeInsets.all(10),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                              color: Colors.cyanAccent),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(10),
                            child: Image(
                              color: Colors.cyan,
                              image: AssetImage(imagePath),
                              fit: BoxFit.cover,
                            ),
                          )),
                      Container(
                        child: SizedBox(
                          width: 20 * _x,
                        ),
                      ),
                      SizedBox(
                          width: 200 * _x,
                          child: Text(
                            title,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(color: Colors.grey),
                          )),
                      Spacer(flex: 1),
                      Container(
                          width: 30 * _y,
                          height: 30 * _y,
                          child: Icon(
                            Icons.arrow_forward_ios,
                            color: Colors.grey,
                          )),
                      SizedBox(
                        width: 10 * _x,
                      )
                    ])
              ],
            )),
      ),
    );
  }

  Widget _customSonglistListView() {
    return Expanded(
      flex: 1,
      child: LayoutBuilder(
        builder: (context, constraints) {
          return SizedBox(
              width: constraints.maxWidth,
              height: constraints.maxHeight,
              child: !_hasLoaded
                  ? Center(
                      child: CircularProgressIndicator(),
                    )
                  : _listOfSonglist.isEmpty
                      ? Center(
                          child: Text(
                            "无自定义歌单",
                            style: TextStyle(
                                color: Colors.blueGrey, fontSize: 20 * _y),
                          ),
                        )
                      : ListView.builder(
                          padding: EdgeInsets.symmetric(vertical: 5),
                          physics: BouncingScrollPhysics(),
                          itemCount: _listOfSonglist?.length ?? 0,
                          itemBuilder: (context, index) => _customSonglistItem(
                              context, _listOfSonglist[index]),
                        ));
        },
      ),
    );
  }

  Widget _customSonglistItem(BuildContext context, SongList songList) {
    return Ink(
      color: Colors.grey[50],
      child: InkWell(
        splashColor: Colors.cyan[100],
        onTap: () => _onTapSonglist(context, songList),
        child: Container(
            padding: EdgeInsets.all(3.0),
            width: _width,
            height: 70 * _y,
            alignment: Alignment.center,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                          alignment: Alignment.center,
                          height: 60 * _y,
                          width: 60 * _y,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(10),
                            child: Image(
                              image: songList.resourceType ==
                                      ImageResourceType.ASSET
                                  ? AssetImage(songList.imagePath)
                                  : songList.resourceType ==
                                          ImageResourceType.NETWORK
                                      ? NetworkImage(songList.imagePath)
                                      : FileImage(File(songList.imagePath)),
                              fit: BoxFit.contain,
                            ),
                          )),
                      Container(
                        child: SizedBox(
                          width: 20 * _x,
                        ),
                      ),
                      SizedBox(
                          width: 200 * _x,
                          child: Text(
                            songList.listName,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(color: Colors.grey),
                          )),
                      Spacer(flex: 1),
                      Container(
                          width: 30 * _y,
                          height: 30 * _y,
                          child: Icon(
                            Icons.arrow_forward_ios,
                            color: Colors.grey,
                          )),
                      SizedBox(
                        width: 10 * _x,
                      )
                    ])
              ],
            )),
      ),
    );
  }

  void _onPressComplete() {
    Navigator.of(context).pop();
  }

  void _onTapSonglist(BuildContext context, SongList songList) {
    Navigator.of(context).push(CustomRoute(
        SongSelectPage(widget._songList, songList),
        CustomRoute.BOTTOM_TO_TOP,
        300));
  }
}

class SongSelectPage extends StatefulWidget {
  final SongList _songList;

  final SongList _openedSonglist;

  SongSelectPage(this._songList, this._openedSonglist);

  @override
  State<StatefulWidget> createState() => _SongSelectPageState();
}

class _SongSelectPageState extends State<SongSelectPage> {
  double _width, _height, _x, _y;

  List<Song> _listOfSong = [];

  List<Song> _source;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    SongsInfo().findSongsWithSongsList(widget._openedSonglist).then((value) {
      _listOfSong = value;
      print('$value');
      SongsInfo().findSongsWithSongsList(widget._songList).then((value) {
        setState(() {
          _source = value;
          print('$value');
        });
      });
      setState(() {});
    });
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    Size size = CommonApi.initParameter(context);
    _width = size.width;
    _height = size.height;
    _x = _width / 420;
    _y = _height / 800;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            height: 20 * _y,
          ),
          _titleBar(),
          _customSonglistListView()
        ],
      ),
    );
  }

  // TODO: 标题栏
  Widget _titleBar() {
    return Container(
      width: _width,
      height: 50 * _y,
      color: Setting.themeColor,
      child: Stack(
        children: [
          Center(
            child: Text(
              widget._songList.listName,
              style: TextStyle(
                  fontSize: 20 * _y,
                  color: Colors.cyan,
                  fontWeight: FontWeight.w800),
            ),
          ),
          Positioned.fill(
              child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Spacer(
                flex: 1,
              ),
              TextButton(
                onPressed: _onPressComplete,
                child: Text(
                  "完成",
                  style: TextStyle(fontSize: 17 * _y, color: Colors.cyan),
                ),
              ),
            ],
          ))
        ],
      ),
    );
  }

  Widget _customSonglistListView() {
    return Expanded(
      flex: 1,
      child: LayoutBuilder(
        builder: (context, constraints) {
          return SizedBox(
              width: constraints.maxWidth,
              height: constraints.maxHeight,
              child: _listOfSong.isEmpty
                  ? Center(
                      child: Text(
                        "歌单内无歌曲 :(",
                        style: TextStyle(
                            color: Colors.blueGrey, fontSize: 20 * _y),
                      ),
                    )
                  : ListView.builder(
                      padding: EdgeInsets.symmetric(vertical: 5),
                      physics: BouncingScrollPhysics(),
                      itemCount: _listOfSong?.length ?? 0,
                      itemBuilder: (context, index) =>
                          _customSonglistItem(context, _listOfSong[index]),
                    ));
        },
      ),
    );
  }

  Widget _customSonglistItem(BuildContext context, Song song) {
    return Ink(
      color: Colors.grey[50],
      child: InkWell(
        splashColor: Colors.cyan[100],
        onTap: () => _onTapSong(song),
        child: Container(
            padding: EdgeInsets.all(3.0),
            width: _width,
            height: 70 * _y,
            alignment: Alignment.center,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(
                        width: 20 * _x,
                      ),
                      SizedBox(
                          width: 200 * _x,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                song.songName,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    color: Colors.cyan,
                                    fontSize: 15 * _y,
                                    fontWeight: FontWeight.w500),
                              ),
                              Text(
                                song.singerName,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    color: Colors.cyan,
                                    fontWeight: FontWeight.w100),
                              )
                            ],
                          )),
                      Spacer(flex: 1),
                      Container(
                          width: 50 * _y,
                          height: 40 * _y,
                          child: _source?.contains(song) ?? true
                              ? Center(
                                  child: Text(
                                    "已添加",
                                    style: TextStyle(color: Colors.blueGrey),
                                  ),
                                )
                              : IconButton(
                                  icon: Icon(Icons.add_box_outlined),
                                  color: Colors.blueGrey,
                                  onPressed: () => _onPressAdd(context, song),
                                )),
                      SizedBox(
                        width: 10 * _x,
                      )
                    ])
              ],
            )),
      ),
    );
  }

  void _onPressComplete() {
    Navigator.of(context).pop();
  }

  _onTapSong(Song song) {
    SongsInfo().addSongIntoSonglist(widget._songList, song).then((value) {
      SongsInfo().findSongsWithSongsList(widget._openedSonglist).then((value) {
        _listOfSong = value;
        print('$value');
        SongsInfo().findSongsWithSongsList(widget._songList).then((value) {
          setState(() {
            _source = value;
            print('$value');
          });
        });
        setState(() {});
      });
    });
  }

  void _onPressAdd(BuildContext context, Song song) {
    SongsInfo().addSongIntoSonglist(widget._songList, song).then((value) {
      SongsInfo().findSongsWithSongsList(widget._openedSonglist).then((value) {
        _listOfSong = value;
        print('$value');
        SongsInfo().findSongsWithSongsList(widget._songList).then((value) {
          _source = value;
          print('$value');
          (context as Element).markNeedsBuild();
        });
        setState(() {});
      });
    });
  }
}
